package com.llyb.chap02;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache{
    Map<String,String> cache = new HashMap();
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void write(String key,String value){

        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t"+"---- 开始写");
            cache.put(key,value);
            System.out.println(Thread.currentThread().getName()+"\t"+"---- 写完成");
        } finally {
            lock.writeLock().unlock();
        }

    }
    public String read(String key){
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t"+"========== 开始读");
            String s = cache.get(key);
            System.out.println(s);
            System.out.println(Thread.currentThread().getName()+"\t"+"========== 读完成");
            return s;
        } finally {
            lock.readLock().unlock();
        }
    }
}

public class ReentrantLockWriteRead {


    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                myCache.write(String.valueOf(i),String.valueOf(i));
            }
        },"AA").start();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                myCache.read(String.valueOf(i));
            }
        },"BB").start();

    }
}
